package com.weiyin.examination.activity;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.weiyin.examination.R;
import com.weiyin.examination.application.Constant;
import com.weiyin.examination.util.LayoutHelper;
import com.weiyin.examination.util.LogUtil;
import com.weiyin.examination.util.SPUtil;
import com.weiyin.examination.util.ToastUtil;
import com.weiyin.examination.util.VerifyCodeUtils;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.Random;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * <pre>
 *     e-mail : niejunfeng@win-electr.com
 *     time   : 2016年6月24日
 *     desc   : app  启动注册登录页面Activity
 *     version: 1.0.5
 *     Copyright: Copyright（c）2017
 *     Company:上海蔚音电子科技有限公司
 * </pre>
 *
 * @author niejunfeng
 */
public class StartVerificationActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = StartVerificationActivity.class.getSimpleName();
    @SuppressLint("StaticFieldLeak")
    public static StartVerificationActivity startVerificationActivity;
    private TextView activityStartVerificationSendCode;
    private EditText activityStartVerificationEdPhone, activityStartLoginEdPhone;
    private String emailOrPho, countries;
    private TextView activityStartLoginSubject;
    /**
     * 是否填写用户个人信息
     */
    private boolean raged;

    private String mark;

    private EventHandler eh;

    private Bitmap bitmap;
    // 短信注册，随机产生头像
    private static final String[] AVATARS = {
            "http://tupian.qqjay.com/u/2011/0729/e755c434c91fed9f6f73152731788cb3.jpg",
            "http://99touxiang.com/public/upload/nvsheng/125/27-011820_433.jpg",
            "http://img1.touxiang.cn/uploads/allimg/111029/2330264224-36.png",
            "http://img1.2345.com/duoteimg/qqTxImg/2012/04/09/13339485237265.jpg",
            "http://diy.qqjay.com/u/files/2012/0523/f466c38e1c6c99ee2d6cd7746207a97a.jpg",
            "http://img1.touxiang.cn/uploads/20121224/24-054837_708.jpg",
            "http://img1.touxiang.cn/uploads/20121212/12-060125_658.jpg",
            "http://img1.touxiang.cn/uploads/20130608/08-054059_703.jpg",
            "http://diy.qqjay.com/u2/2013/0422/fadc08459b1ef5fc1ea6b5b8d22e44b4.jpg",
            "http://img1.2345.com/duoteimg/qqTxImg/2012/04/09/13339510584349.jpg",
            "http://img1.touxiang.cn/uploads/20130515/15-080722_514.jpg",
            "http://diy.qqjay.com/u2/2013/0401/4355c29b30d295b26da6f242a65bcaad.jpg"
    };
    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 100:
                    ToastUtil.showTextToast(StartVerificationActivity.this, "已发送验证码");
                    break;
                case -1:
                    ToastUtil.showTextToast(StartVerificationActivity.this, (String) msg.obj);
                    break;
                case 101:
                    ToastUtil.showTextToast(StartVerificationActivity.this, "已登录");
                    finish();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start_verification);
        startVerificationActivity = this;
        LayoutHelper layoutHelper = new LayoutHelper(this);
        layoutHelper.scaleView(findViewById(R.id.activityStartVerificationLayout));
        initView();
        initMob();
    }

    private void initView() {
        ImageView back = (ImageView) findViewById(R.id.back);
        activityStartLoginEdPhone = (EditText) findViewById(R.id.activityStartLoginEdPhone);
        activityStartVerificationEdPhone = (EditText) findViewById(R.id.activityStartVerificationEdPhone);
        activityStartVerificationSendCode = (TextView) findViewById(R.id.activityStartVerificationSendCode);
        activityStartLoginSubject = (TextView) findViewById(R.id.activityStartLoginSubject);

        activityStartVerificationSendCode.setOnClickListener(this);
        activityStartLoginSubject.setOnClickListener(this);
        back.setOnClickListener(this);
        activityStartVerificationEdPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (StringUtils.isEmpty(s.toString())) {
                    activityStartLoginSubject.setSelected(false);
                } else {
                    activityStartLoginSubject.setSelected(true);
                }
            }
        });
    }

    private void initMob() {
        eh = new EventHandler() {

            @Override
            public void afterEvent(int event, int result, Object data) {
                if (event == SMSSDK.EVENT_SUBMIT_USER_INFO) {
                    // 短信注册成功后，返回MainActivity,然后提示新好友
                    if (result == SMSSDK.RESULT_COMPLETE) {
                        LogUtil.i(TAG, "资料已提交");
                        String code = activityStartVerificationEdPhone.getText().toString();
                        SMSSDK.submitVerificationCode(countries, emailOrPho, code);
                    } else {
                        ((Throwable) data).printStackTrace();
                    }
                }
                if (result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交验证码成功
                        LogUtil.i(TAG, "提交验证码成功");
                        SPUtil.getSharedPreferencesData(StartVerificationActivity.this, Constant.NICKNAME, emailOrPho);
                        SPUtil.getSharedPreferencesData(StartVerificationActivity.this, Constant.UNION_ID, emailOrPho);
                        Message message = new Message();
                        message.what = 101;
                        mHandler.sendMessage(message);
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        //获取验证码成功
                        Message message = new Message();
                        message.what = 100;
                        mHandler.sendMessage(message);
                        LogUtil.i(TAG, "获取验证码成功");
                    } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                        //返回支持发送验证码的国家列表
                    }
                } else {
                    ((Throwable) data).printStackTrace();
                    try {
                        Message message = new Message();

                        JSONObject jsonObject = new JSONObject(((Throwable) data).getMessage());
                        message.what = -1;
                        message.obj = jsonObject.getString("detail");
                        mHandler.sendMessage(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        };
        /* 注册短信回调 */
        SMSSDK.registerEventHandler(eh);
    }

    /**
     * 提交用户信息
     *
     * @param country 城市
     * @param phone   手机号
     */
    private void registerUser(String country, String phone) {
        Random rnd = new Random();
        int id = Math.abs(rnd.nextInt());
        String uid = String.valueOf(id);
        String nickName = "SmsSDK_User_" + uid;
        String avatar = AVATARS[id % 12];
        SMSSDK.submitUserInfo(uid, nickName, avatar, country, phone);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(eh);
        if (startVerificationActivity != null) {
            startVerificationActivity = null;
        }
        if (bitmap != null) {
            bitmap.recycle();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.activityStartVerificationSendCode:
                emailOrPho = activityStartLoginEdPhone.getText().toString();
                countries = "+86";
                if (StringUtils.isEmpty(emailOrPho)) {
                    ToastUtil.showTextToast(this, getString(R.string.errorEnterEmailOrPhoneNumber));
                    return;
                }
                VerifyCodeUtils.sendCode(this, activityStartVerificationSendCode);
                SMSSDK.getVerificationCode(countries, emailOrPho);
                break;
            case R.id.activityStartLoginSubject:
                String code = activityStartVerificationEdPhone.getText().toString();
                if (StringUtils.isEmpty(code)) {
                    ToastUtil.showTextToast(this, getString(R.string.notCode));
                    return;
                }
                registerUser("+86", emailOrPho);
                break;
            default:
                break;
        }
    }
}
